package com.hongmeng.operater.service.operaterUser.impl;

import java.util.Date;
import java.util.List;

import com.hongmeng.common.constant.Constants;
import com.hongmeng.common.constant.UserConstants;
import com.hongmeng.common.core.domain.AjaxResult;
import com.hongmeng.common.core.domain.entity.SysRole;
import com.hongmeng.common.core.domain.entity.SysUser;
import com.hongmeng.common.exception.BaseException;
import com.hongmeng.common.utils.DateUtils;
import com.hongmeng.common.utils.SecurityUtils;
import com.hongmeng.operater.domain.operaterUser.SaveCustomer;
import com.hongmeng.operater.mapper.operaterUser.HmCustomerExtMapper;
import com.hongmeng.system.mapper.SysRoleMapper;
import com.hongmeng.system.mapper.SysUserExtMapper;
import com.hongmeng.system.mapper.SysUserRoleMapper;
import com.hongmeng.system.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hongmeng.operater.mapper.operaterUser.HmCustomerMapper;
import com.hongmeng.operater.domain.operaterUser.HmCustomer;
import com.hongmeng.operater.service.operaterUser.IHmCustomerService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 企业信息Service业务层处理
 * 
 * @author hongmeng
 * @date 2021-01-18
 */
@Slf4j
@Service
public class HmCustomerServiceImpl implements IHmCustomerService 
{

    @Autowired
    private HmCustomerMapper hmCustomerMapper;

    @Autowired
    private HmCustomerExtMapper hmCustomerExtMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private SysUserExtMapper userExtMapper;

    /**
     * 查询企业信息
     * 
     * @param customId 企业信息ID
     * @return 企业信息
     */
    @Override
    public HmCustomer selectHmCustomerById(Integer customId)
    {
        return hmCustomerMapper.selectHmCustomerById(customId);
    }

    /**
     * 查询企业信息列表
     * 
     * @param hmCustomer 企业信息
     * @return 企业信息
     */
    @Override
    public List<HmCustomer> selectHmCustomerList(HmCustomer hmCustomer)
    {
        return hmCustomerMapper.selectHmCustomerList(hmCustomer);
    }

    /**
     * 新增企业信息
     * 
     * @param addCustomer 企业信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult insertHmCustomer(SaveCustomer addCustomer)
    {
        String createBy="";
        Date nowTime = DateUtils.getNowDate();
        if (SecurityUtils.isLogin()){
            createBy = SecurityUtils.getUsername();
        }
        //新增企业的用户信息
        SysUser user = new SysUser();
        user.setNickName(addCustomer.getCustomerName());
        user.setUserName(addCustomer.getCustomerNo());
        user.setPassword(SecurityUtils.encryptPassword(Constants.DEFAULT_PASS_WORD));
        user.setPhonenumber(addCustomer.getContactMobile());
        user.setEmail(addCustomer.getEmail());
        user.setStatus(Constants.USER_STATE.NORMAL);//初始状态正常
        //用户类型为企业用户
        user.setUserType(Constants.USER_TYPE.CUSTOMER);
        user.setCreateBy(createBy);
        user.setCreateTime(nowTime);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            log.error("新增企业'" + addCustomer.getCustomerNo() + "'失败，企业号账号已存在");
            throw new BaseException("新增企业'" + addCustomer.getCustomerNo() + "'失败，企业号账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            log.error("新增企业'" + user.getUserName() + "'失败，手机号码已存在");
            throw new BaseException("新增企业'" + user.getUserName() + "'失败，手机号码已存在");
        }
        userService.insertUser(user);
        //用户角色为企业
        SysRole selectRole = new SysRole();
        selectRole.setRoleKey(Constants.ROLE_KEY.CUSTOMER);
        List<SysRole> selectRoleList = sysRoleMapper.selectRoleList(selectRole);
        if (selectRoleList.size()!=1){
            log.error("不存在企业用户角色");
            throw new BaseException("新增企业出现问题，请联系管理员");
        }
        Long[] roleIds = {selectRoleList.get(0).getRoleId()};
        user.setRoleIds(roleIds);
        userService.insertUserRole(user);
        //新增企业信息
        HmCustomer customer = new HmCustomer();
        BeanUtils.copyProperties(addCustomer,customer);
        customer.setUserId(user.getUserId());
        customer.setCreateBy(createBy);
        customer.setCreateTime(nowTime);
        int customerCount = hmCustomerMapper.insertHmCustomer(customer);
        log.info("新增企业用户共{}条,企业id:{},用户id{}",customerCount,customer.getId(),user.getUserId());
        return AjaxResult.success(customer);
    }

    /**
     * 修改企业信息
     * 
     * @param updateCustomer 企业信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult updateHmCustomer(SaveCustomer updateCustomer)
    {
        log.info("修改企业信息，传入企业id为："+updateCustomer.getId());
        String updateBy="";
        Date nowTime = DateUtils.getNowDate();
        if (SecurityUtils.isLogin()){
            updateBy = SecurityUtils.getUsername();
        }
        HmCustomer customer = hmCustomerMapper.selectHmCustomerById(updateCustomer.getId());
        if (customer==null){
            log.error("无法获取id为:{}的企业信息",updateCustomer.getId());
            throw new BaseException("无法获取id为："+updateCustomer.getId()+"的企业信息");
        }
        SysUser user = userService.selectUserById(customer.getUserId());
        if (user == null){
            log.error("当前企业数据存在问题，请反馈给管理员");
            throw new BaseException("当前企业数据存在问题，请反馈给管理员");
        }
        //修改企业用户信息
        user.setNickName(updateCustomer.getCustomerName());
        user.setPhonenumber(updateCustomer.getContactMobile());
        user.setEmail(updateCustomer.getEmail());
        user.setUpdateBy(updateBy);
        user.setUpdateTime(nowTime);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return AjaxResult.error("修改企业'" + updateCustomer.getCustomerNo() + "'失败，企业号账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改企业'" + user.getUserName() + "'失败，手机号码已存在");
        }
        userService.updateUser(user);
        //修改企业信息
        BeanUtils.copyProperties(updateCustomer,customer);
        customer.setUpdateBy(updateBy);
        customer.setUpdateTime(nowTime);
        int customerCount = hmCustomerExtMapper.updateHmCustomer(customer);

        log.info("更新企业用户共{}条,企业id:{},用户id{}",customerCount,customer.getId(),user.getUserId());
        return AjaxResult.success(customer);
    }

    /**
     * 批量删除企业信息
     * 
     * @param customIds 需要删除的企业信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHmCustomerByIds(Integer[] customIds)
    {
        int count=0;
        //删除企业的用户信息
        for (Integer customId :customIds) {
            count+=deleteHmCustomerById(customId);
        }
        log.info("删除企业信息共{}条",count);
        return count;
    }

    /**
     * 删除企业信息信息
     * 
     * @param customId 企业信息ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHmCustomerById(Integer customId)
    {
        HmCustomer customer = hmCustomerMapper.selectHmCustomerById(customId);
        if (customer==null){
            log.error("没有id为"+customId+"的企业信息。");
            throw new BaseException("没有id为"+customId+"的企业信息");
        }
        userService.checkUserAllowed(new SysUser(customer.getUserId()));
        userService.deleteUserById(customer.getUserId());
        //删除用户角色信息
        return hmCustomerMapper.deleteHmCustomerById(customId);
    }
}
